package io.github.wanggit.antrpc.console.service.impl;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import io.github.wanggit.antrpc.console.service.AccountService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Objects;
import java.util.UUID;

@Service
public class AccountServiceImpl implements AccountService {

    @Value("${console.default.user-name}")
    private String userName;

    @Value("${console.default.password}")
    private String password;

    private Cache<String, String> tokenCache = CacheBuilder.newBuilder().build();

    @Override
    public String checkAccount(String userName, String password) {
        if (Objects.equals(this.userName, userName) && Objects.equals(this.password, password)) {
            String token = UUID.randomUUID().toString();
            tokenCache.put(token, token);
            return token;
        }
        return null;
    }

    @Override
    public boolean checkToken(String token) {
        if (null != token) {
            String value = tokenCache.getIfPresent(token);
            return null != value && Objects.equals(value, token);
        }
        return false;
    }
}
